#include "Arduino.h"
#include "ArduinoJson.h"
#include "FS.h"
#include "SPIFFS.h"
#include "serial_debug.h"
#include "drv_cfg_tool.h"

/************* 变量 *************/
WiFi_Config_t* pWiFi_Config = NULL;
MQTT_Config_t* pMQTT_Config = NULL;


/************* 静态变量与声明 *************/
static bool is_initialized = false;

static bool cfg_read_wifi_json(void);
static bool cfg_read_mqtt_json(void);


bool drv_cfg_tool_init(void) {
  if (is_initialized == true) {
    return true;
  }

  if (esp_spiram_get_chip_size == 0) {
    PRINT_INFO("PSRAM 好像没找到");
    return false;
  }

  pWiFi_Config = (WiFi_Config_t*)ps_malloc(sizeof(WiFi_Config_t));
  pMQTT_Config = (MQTT_Config_t*)ps_malloc(sizeof(MQTT_Config_t));

  if (pWiFi_Config == NULL | pMQTT_Config == NULL) {
    PRINT_INFO("PSRAM 申请内存好像出错咯");
    return false;
  }

  is_initialized = true;
  return true;
}

bool cfg_read_config_from_spiffs(void) {
  if (is_initialized == false) {
    PRINT_INFO("CFG 内存还未初始化");
    return false;
  }

  if (!SPIFFS.begin(true)) {  // Pass true to format if initialization fails
    PRINT_INFO("SPIFFS 初始化失败");
    return false;
  }

  if (!cfg_read_wifi_json()) {
    return false;
  }
  if (!cfg_read_mqtt_json()) {
    return false;
  }

  return true;
}

static bool cfg_read_wifi_json(void) {
  File file = SPIFFS.open("/WiFi_cfg.json", "r"); // Replace with your file name
  if (!file) {
    PRINT_INFO("SPIFFS 打开WiFi配置文件失败");
    return false;
  }

  size_t file_size = file.size();
  PRINT_INFO("文件大小" + String(file_size));
  char* str = (char*)malloc(file_size);
  PRINT_INFO("申请内存");
  file.read((uint8_t*)str, file_size);
  PRINT_INFO("读取数据");
  file.close();
  PRINT_INFO("关闭文件");

  JsonDocument doc;
  PRINT_INFO("json doc");
  deserializeJson(doc, str, file_size);
  free(str);
  PRINT_INFO("反序列化");

  
  pWiFi_Config->WiFi_mode = doc["mode"];
  PRINT_INFO("获取参数");
  
  const char* temp_char;

  temp_char = doc["client ssid"];
  strcpy(pWiFi_Config->client_ssid, temp_char);

  temp_char = doc["client password"];
  strcpy(pWiFi_Config->client_password, temp_char);

  temp_char = doc["ap ssid"];
  strcpy(pWiFi_Config->ap_ssid, temp_char);

  temp_char = doc["ap password"];
  strcpy(pWiFi_Config->ap_password, temp_char);


  return true;
}

static bool cfg_read_mqtt_json(void) {
  File file = SPIFFS.open("/MQTT_cfg.json", "r"); // Replace with your file name
  if (!file) {
    PRINT_INFO("SPIFFS 打开MQTT配置文件失败");
    return false;
  }

  size_t file_size = file.size();
  char* str = (char*)malloc(file_size);
  file.read((uint8_t*)str, file_size);
  file.close();

  JsonDocument doc;
  deserializeJson(doc, str, file_size);

  pMQTT_Config->port = doc["port"];
  
  const char* temp_char;

  temp_char = doc["url"];
  strcpy(pMQTT_Config->url, temp_char);

  temp_char = doc["user name"];
  strcpy(pMQTT_Config->username, temp_char);

  temp_char = doc["password"];
  strcpy(pMQTT_Config->password, temp_char);

  free(str);

  return true;
}
